/**
 * 通用脚本
 */
layui.define(['layer', 'form', 'table'], function (exports) {

    var $ = layui.$;
    var table = layui.table;

    table.on('toolbar(buttonClick)', function (obj) {
        if (obj.event === 'refresh') {
            plugins.reloadTableBox(obj.config.url);
        } else if (obj.event === 'add') {
            plugins.buildAjax({
                url: 'add', data: {}
            }, 'index');
        } else if (obj.event === 'batchDelete') {
            var checkStatus = table.checkStatus(obj.config.id),
                data = plugins.getJsonObjectKeyValue(checkStatus.data, 'id');
            if (data.length === 0) {
                layer.msg('请选择一行');
            } else {
                var warning = '您确定要 <span style="color:#f56954">批量删除</span> 吗？';
                layer.confirm(warning, function () {
                    $.post('batch_delete', {row: data}, function (result) {
                        layer.msg(result.msg);
                        plugins.reloadTableBox(obj.config.url);
                    }, 'json');
                });
            }
        }
    });

    var plugins = {

        // 获取json对象中某一字段域集合的值
        getJsonObjectKeyValue: function (data, key) {
            // 如果为空，直接返回空数组
            if (data.length === 0) {
                return [];
            }
            // 数据遍历
            var dataArray = [];
            for (var i in data) {
                dataArray.push(data[i][key]);
            }
            return dataArray;
        },

        // 表格默认配置
        tableOption: function (customerOption) {
            return $.extend({}, {
                elem: '#showDataTable',
                parseData: function (res) {
                    return {
                        "code": res.code,
                        "msg": res.message,
                        "count": res.data.count,
                        "data": res.data.rows
                    }
                },
                toolbar: '#toolBar',
                defaultToolbar: [],
                id: 'tableBox',
                cols: [],
                limit: 20,
                limits: [15, 20, 25, 30],
                loading: true,
                page: true,
                even: true,
                size: 'lm'
            }, customerOption)
        },

        // 刷新表格
        reloadTableBox: function (reloadUrl) {
            table.reload('tableBox', {url: reloadUrl});
        },

        // ajax请求数据格式化处理
        requestOptionsInit: function (options) {
            if (options.hasOwnProperty('uid')) {
                options.url = options.url + '/' + options.rid;
            }
            return options;
        },

        // AJAX数据请求封装
        buildAjax: function (options, activeUrl, requestType) {
            var options = this.requestOptionsInit(options);
            // 基础配置
            var ajaxOptions = {
                type: requestType || 'GET',
                data: {},
                success: function (response) {
                    if (typeof response === 'object') {
                        if (0 === response.code) {
                            plugins.toastr.success(response.msg, {}, function () {
                                if (response.data.hasOwnProperty('reload') && 'all' === response.data.reload) {
                                    location.reload();
                                } else {
                                    this.reloadTableBox(activeUrl);
                                }
                            });
                        } else {
                            plugins.toastr.fail(response.msg, {}, {});
                        }
                        return false;
                    } else {
                        plugins.openResponseHtml(response, {
                            title: plugins.checkStringIncludeKeyWord(options.url),
                            reloadUrl: activeUrl,
                            action: options.url
                        });
                    }
                }
            };
            // 数据请求
            $.ajax($.extend({}, ajaxOptions, options));
        },

        // 判断字符串是否包含指定的关键字
        checkStringIncludeKeyWord: function (string) {
            if (RegExp(/add/).test(string)) {
                return '新增';
            }
            if (RegExp(/edit/).test(string)) {
                return '编辑';
            }
        },

        // 打开返回HTML
        openResponseHtml: function (html, callback) {
            parent.layer.open({
                type: 1,
                title: callback.title,
                content: html,
                scrollbar: false,
                area: ['auto', 'auto'],
                maxHeight: '80%',
                maxWidth: '80%',
                btn: ['确定', '取消'],
                yes: function (index, layero) {
                    if ($(layero).find('.layui-layer-btn0').attr('disabled')) {
                        return false;
                    }
                    $(layero).find('.layui-layer-btn0').attr('disabled', 'disabled');
                    var form = $(layero).find('form');
                    var method = thisForm.attr('method') || 'POST';
                    $.ajax({
                        type: method,
                        url: callback.action,
                        data: form.serialize(),
                        success: function (result) {
                            if (result.code === 0) {
                                plugins.toastr.success(result.message, {}, function () {
                                    layer.close(index);
                                    if (result.data.hasOwnProperty('reload') && 'all' === result.data.reload) {
                                        location.reload();
                                    } else {
                                        plugins.reloadTableBox(callback.reloadUrl);
                                    }
                                });
                            } else {
                                var failMessage = result.message || '服务器异常';
                                plugins.toastr.fail(failMessage, {}, function () {
                                    $(layero).find('.layui-layer-btn0').removeAttr('disabled');
                                });
                            }
                        }
                    });
                },
                btn2: function (index) {
                    layer.close(index);
                },
                success: function () {
                    layui.form.render();
                }
            }, 'html');
        },

        flag: function (value) {
            value = value.role === null ? '' : value.role.toString();
            var colorArr = {index: 'success', hot: 'warning', recommend: 'danger', 'new': 'info'};
            //渲染Flag
            var html = [];
            var arr = value.split(',');
            $.each(arr, function (i, value) {
                value = value === null ? '' : value.toString();
                if (value == '')
                    return true;
                var color = value && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'layui-bg-black';
                value = value.charAt(0).toUpperCase() + value.slice(1);
                html.push('<span class="layui-badge ' + color + '">' + value + '</span>');
            });
            return html.join(' ');
        },

        // 格式化标签
        labelBuild: function (value) {
            return plugins.flag.call(this, value);
        },

        // 弹出框
        toastr: {
            success: function (message, config, callback) {
                var msgConfig = {time: 1000, icon: 6, offset: '50px'};
                var options = $.extend({}, msgConfig, config);
                layer.msg(message, options, callback);
            },
            fail: function (message, config, callback) {
                var msgConfig = {time: 2000, icon: 5, offset: '50px'};
                var options = $.extend({}, msgConfig, config);
                layer.msg(message, options, callback);
            }
        }
    };

    // 返回扩展对象
    exports('plugins', plugins);
});